<template>
<!-- 抽屉式弹框 -->
  <el-drawer
    title="组织管理新增"
    :before-close="handleClose"
    :visible.sync="dialogOrganizationVisible"
    direction="rtl"
    custom-class="demo-drawer"
    ref="drawer"
    :wrapperClosable="false"
    :close-on-press-escape="false"
  >
    <div class="demo-drawer__content">
      <el-card class="box-card boxCard">
        <div slot="header" class="clearfix">
          <el-input v-model="orgNameSearch" placeholder="请搜索..." suffix-icon="el-icon-search"></el-input>
        </div>
        <div class="text item">
          <el-tree
            v-show="orgNameSearch"
            :data="orgSearchDatas"
            :default-expanded-keys="treeExpandedKey"
            :props="orgTreeProps"
            :load="loadOrgTreeData"
            :check-strictly="true"
            :check-on-click-node="true"
            show-checkbox
            @check-change="handleCheckChange"
            :ref="orgNameSearch?'orgTree':''"
            :highlight-current="true"
            node-key="orgId"
            >
          </el-tree>
          <el-tree
            v-show="!orgNameSearch"
            :default-expanded-keys="treeExpandedKey"
            :default-checked-keys="defaultChecked"
            :props="orgTreeProps"
            :load="loadOrgTreeData"
            :check-strictly="true"
            :check-on-click-node="true"
            lazy
            show-checkbox
            @check-change="handleCheckChange"
            :ref="!orgNameSearch?'orgTree':''"
            :highlight-current="true"
            node-key="orgId"
            :key="treeKey"
            >
          </el-tree>
        </div>
      </el-card>
      <div class="demo-drawer__footer dialogFooter">
        <el-button type="primary" @click="handleCheck(true)">
          确定
          <i class="el-icon-document-checked el-icon--right"></i>
        </el-button>
        <el-button @click="handleCheck(false)">
          取消
          <i class="el-icon-refresh-left"></i>
        </el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import { Tree, Dialog, MessageBox, Message, TabPane, Collapse, CollapseItem, Tag, Drawer } from 'element-ui'
import { organizationRoot, organizationParent, organizationSearch, tieUserGroupDataAuth } from '@/api/authority/userAuthorization/userAuthorization.js'
export default {
props: ['dialogOrganizationVisible', 'dialogOrganizationGroup', 'orgDate'],
data () {
  return {
    treeKey: 1, // 重新加载树形数据
    orgSearchDatas: [], // 搜索返回的树形数据
    orgNameSearch: '', // 根据组织名称模糊搜索
    treeExpandedKey: [230], // 默认展开的树形节点
    defaultChecked: [], // 默认选中的项
    nowCheckArr: [], // 当前选中的项
    // 组织树默认配置
    orgTreeProps: {
      label: 'orgName',
      isLeaf: 'isLeaf'
    },
    orgId: [] // 获取到的组织id
  }
},
watch: {
  orgDate: {
    deep: true,
    immediate: true,
    handler(newVal) {
      let arr = []
      newVal.forEach(v => arr.push(v.roleId - 0))
      this.defaultChecked = arr
    },
  },
  orgNameSearch (val) {
    if (val) {
      organizationSearch(val).then(res => {
        let orgDatas = res.data.data
        this.deepChild(orgDatas)
        this.orgSearchDatas = orgDatas
      });
    }else{
      this.treeKey+=1
    }
  }
},
methods: {
  /* 递归遍历树形数据源 */
  deepChild (val) {
    let $this = this
    if (val && Array.isArray(val) && val.length) {
      val.forEach(item => {
        if (typeof item === 'object') {
          item.orgId = item.id
          item.orgName = item.name
          $this.deepChild(item.children)
        }
      })
    }
  },
  /* 加载组织树 */
    loadOrgTreeData (node, resolve) {
      if (node.level == 0) {
        organizationRoot().then(res => {
          let orgDatas = res.data.data
          orgDatas.forEach(e => {
            if (this.defaultChecked.some(v => e.orgId == v)) e.disabled = true // 判断是否禁用(不可取消勾选)
            if (e.isLeaf == 'n') {
              e.isLeaf = false
            } else {
              e.isLeaf = true
            }
          })
          resolve(orgDatas)
          this.$refs.orgTree.setCurrentKey(orgDatas[0].orgId)
          this.treeExpandedKey = [orgDatas[0].orgId]
        });
      } else {
        let id = node.data.orgId
        organizationParent(id).then(res => {
          console.log(res)
          let orgDatas = res.data.data.records
          orgDatas.forEach(e => {
            if (this.defaultChecked.some(v => e.orgId == v)) e.disabled = true // 判断是否禁用(不可取消勾选)
            if (e.isLeaf == 'n') {
              e.isLeaf = false
            } else {
              e.isLeaf = true
            }
          })
          resolve(orgDatas)
        })
        .catch(res => {
          resolve([])
        })
      }
    },
    // 弹框关闭提示框
    handleClose () {
      // MessageBox.confirm('确认要关闭弹框吗？')
      //   .then(() => {
          this.$refs.orgTree.setCheckedKeys([]) // 点击取消按钮时取消tree1选中的数据
          this.orgNameSearch = '' // 点击取消按钮时 清空搜索框还原到tree1显示
          this.$emit('dialogHideOrganization', false)
        // })
        // .catch(() => {})
    },
    // 弹框点击按钮
    handleCheck (result) {
      if (!result) {
        return this.handleClose()
      } else {
        let authIds = []
        this.orgDate.forEach(v => authIds.push(v.roleId))
        this.orgId.forEach(v => {
          let isRepeace = false
          for (let i = 0; i < this.orgDate.length; i++) {
            if (this.orgDate[i].roleId == v) {
              isRepeace = true
              break
            }
          }
          if (!isRepeace) authIds.push(v)
        })
        tieUserGroupDataAuth({
          authIds: authIds,
          id: this.dialogOrganizationGroup,
          type: '572fe77cca7649319ca2e324fae0779a'
        }).then(res => {
          // console.log(res)
          if (res.data.code === 10000) {
            Message.success('新增成功')
            let tempArr = [].concat(this.nowCheckArr)
            this.$refs.orgTree.setCheckedKeys([]) // 点击确定按钮时把选中数据传到父页面再取消tree1选中的数据
            this.orgNameSearch = '' // 点击确定按钮时把选中数据传到父页面再清空搜索框还原到tree1显示
            this.$emit('dialogHideOrganization',tempArr)
          }
        })
        // return this.$emit('dialogHideOrganization', false)
      }
    },
    // 选中树节点
    handleCheckChange (data, checked, indeterminate) {
      console.log(data, checked, indeterminate)
      if (!checked) {
        // 如果取消选中，就把当前记录的那个节点对象orgId清掉
        for (let i = 0; i < this.nowCheckArr.length; i++) {
          if (this.nowCheckArr[i].orgId === data.orgId) {
            this.nowCheckArr.splice(i, 1)
            break
          }
        }
      } else { // 是选中了
        // this.$refs.orgTree.setCheckedNodes([data])
        this.nowCheckArr.push(data)
      }
      let orgIdNew = []
      this.nowCheckArr.forEach(e => {
        console.log(e.orgId)
        orgIdNew.push(e.orgId)
      })
      this.orgId = orgIdNew
    }
  },
  components: {
    'el-tree': Tree,
    'el-dialog': Dialog, // 对话框
		'el-tab-pane': TabPane, // 标签页
		'el-collapse': Collapse, // 折叠面板
		'el-collapse-item': CollapseItem, // 折叠面板列
    'el-tag': Tag, // 标签
    'el-drawer': Drawer // 对话框
  },
}
</script>
<style lang="scss">
.dialogCard{
  border: none;
  box-shadow: none;
  .el-card__body{
    padding: 0;
  }
  .checkbox{
    .el-checkbox {
      margin: 6px 0 6px 10px;
    }
  }
}
.dialogCard.is-always-shadow{
  -webkit-box-shadow: none; 
  box-shadow: none;
}
.dialogFooter {
  position: fixed;
  bottom: 10px;
  right: 10px;
}
</style>